package ui.activity.poscontrol;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;

import net.ck.hzq.R;
import net.ck.hzq.TobuyApplication;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import Utils.ToastUtil;
import base.BaseAct;
import base.BaseBiz;
import butterknife.BindView;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import dao.BackFlowDevicesInput;
import event.HasPushEvent;
import event.NetErrorEvent;
import event.PosControlEvent;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import ui.activity.poscontrol.adapter.PushBackPeopleAdapter;
import ui.activity.poscontrol.beanmodel.PosMainBean;
import ui.activity.poscontrol.beanmodel.PushBackPeopleBean;
import ui.activity.poscontrol.beanmodel.PushBackPosBean;
import ui.activity.poscontrol.biz.PosControlMainBiz;
import ui.activity.poscontrol.component.DaggerPosControlMainComponent;
import ui.activity.poscontrol.contract.PosControlMainContract;
import ui.activity.poscontrol.module.PosControlMainModule;
import ui.activity.poscontrol.presenter.PosControlMainPresenter;


/**
 * 可回拨终端列表
 * Created by chenjian on 18/2/22.
 */

public class PushBackControlAct extends BaseAct implements PosControlMainContract.View {

    @Inject
    PosControlMainPresenter presenter;
    @Inject
    PosControlMainBiz biz;


    @BindView(R.id.posrecord_txt_total)
    TextView posrecord_txt_total;
    @BindView(R.id.posrecord_txt_jh)
    TextView posrecord_txt_jh;
    @BindView(R.id.pushback_btn)
    TextView pushback_btn;
    @BindView(R.id.pull_refresh_ptr)
    PtrClassicFrameLayout ptr;
    @BindView(R.id.pushpeople_list)
    RecyclerView pushpeople_list;
    private List<BackFlowDevicesInput.SnInfoBean> snInfo = new ArrayList<>();
    public List<String> mSelectedDevices = new ArrayList<>();
    private List<PushBackPeopleBean> userInfoData = new ArrayList<>();
    PushBackPeopleAdapter adapter;
    @Override
    protected void setRoot() {
        setContentView(R.layout.activity_pushback);
    }

    @Override
    protected void setup() {
        DaggerPosControlMainComponent.builder().posControlMainModule(new PosControlMainModule(this)).build().inject(this);
        setToolBar("可回拨终端列表", "");
        pushpeople_list.setLayoutManager(new LinearLayoutManager(PushBackControlAct.this));
        presenter.setBiz(biz);
        InitData();
        pushback_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pushback_btn.setClickable(false);
                submit();
            }
        });

        ptr.setLastUpdateTimeRelateObject(this);
        ptr.disableWhenHorizontalMove(true);
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                InitData();
            }
        });

    }

    private void InitData(){
        userInfoData.clear();
        biz.querhBackPeopleData(TobuyApplication.getCustomId(),new BaseBiz.Callback<List<PushBackPeopleBean>>() {
            @Override
            public void onSuccess(List<PushBackPeopleBean> posMainBean) {
                ptr.onRefreshComplete();
                userInfoData.addAll(posMainBean);
                int totalsize = 0;
                for (int i = 0;i<posMainBean.size();i++){
                    totalsize+=posMainBean.get(i).getCount();

                }
                posrecord_txt_total.setText("终端数量："+totalsize+"台");
//                if(null == adapter){
                    adapter= new PushBackPeopleAdapter(PushBackControlAct.this,posMainBean);
                    pushpeople_list.setAdapter(adapter);
//                }else{
//                    adapter.notifyDataSetChanged();
//                }

            }

            @Override
            public void onFailure(List<PushBackPeopleBean> getUrlOutput) {
                ptr.onRefreshComplete();
            }

        });
    }
    private void submit(){
            BackFlowDevicesInput input = new BackFlowDevicesInput();
            input.setCustomerId(TobuyApplication.getCustomId());
            input.getSnInfo().addAll(snInfo);

            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(input));
            biz.backFlowDevices(requestBody, new BaseBiz.Callback<Object>() {
                @Override
                public void onSuccess(Object info) {
                    ToastUtil.show(PushBackControlAct.this,"回拨成功");
                    finish();
                }
                @Override
                public void onFailure(Object info) {
                    pushback_btn.setClickable(true);
                }
            });
    }
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(PosControlEvent event) {
        mSelectedDevices.clear();
        snInfo.clear();
        for (int i = 0;i<userInfoData.size();i++){
         for (int j = 0;j<userInfoData.get(i).getPosRecords().size();j++){
             if(userInfoData.get(i).getPosRecords().get(j).isIsselect()){
                 mSelectedDevices.add(userInfoData.get(i).getPosRecords().get(j).getSn());
                 boolean hastargetId = false;
                 int tagk = 0;
                 for (int k = 0;k<snInfo.size();k++ ){
                     if(null!=snInfo&&snInfo.size()>0&&userInfoData.get(i).getFromId() == snInfo.get(k).getTargetId()){
                         hastargetId = true;
                         tagk = k;
                     }
                 }
                 if(hastargetId){
                     snInfo.get(tagk).getSnList().add(userInfoData.get(i).getPosRecords().get(j).getSn());
                 }else{
                     BackFlowDevicesInput.SnInfoBean snInfoBean = new BackFlowDevicesInput.SnInfoBean();
                     snInfoBean.setTargetId(userInfoData.get(i).getFromId());
                     snInfoBean.getSnList().add(userInfoData.get(i).getPosRecords().get(j).getSn());
                     snInfo.add(snInfoBean);
                 }

             }
         }
        }
        posrecord_txt_jh.setText("已选择：" + mSelectedDevices.size()+"台");
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void registerCancelOrder(HasPushEvent event) {
        biz.queryPushBackPosData(TobuyApplication.getCustomId(),event.toId,1,10000,"","",new BaseBiz.Callback<PushBackPosBean>() {
            @Override
            public void onSuccess(PushBackPosBean pushPosBean) {
                for ( int i = 0;i<userInfoData.size();i++){
                    if(userInfoData.get(i).getFromId() == event.toId) {
                        userInfoData.get(i).getPosRecords().clear();
                        userInfoData.get(i).getPosRecords().addAll(pushPosBean.getRecords());
                        break;
                    }
                }
                adapter.setData(userInfoData);

            }

            @Override
            public void onFailure(PushBackPosBean pushPosBean) {

            }

        });
    }
    @Override
    protected void init(@Nullable Bundle savedInstanceState) {


    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
        TobuyApplication.piliangPosition.clear();
    }




    @Override
    public void upDateUI(PosMainBean bean) {
//        my_pos_num.setText(bean.getPosCount()+"台");
//        posrecord_txt_total.setText("终端数量："+(bean.getPosCount()+bean.getFlowCount())+"台");
//        posopen_txt_total.setText("已开通："+bean.getOpenedCount()+"台");
//        posrecord_txt_jh.setText("已激活"+bean.getActiveCount()+"台");
//        push_pos_num.setText(bean.getFlowCount()+"台");
    }

    @Override
    public void showPopWindow() {
    }

    @Override
    public void showFlowRuleDialog(String items) {
    }
}
